//
//  CYUserAccountViewModel.swift
//  WeiBo
//
//  Created by Mr_J on 16/3/7.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
//
//private let CY_APPKEY = "3782997027"
//private let CY_REDIRECT_URL = "https://www.baidu.com/"
//private let CY_APPSECRET = "27b827ebb69e9cee419131b3f29f291b"

class CYUserAccountViewModel: NSObject {

    var userLogin: Bool {
        if self.accessToken != nil && !self.isExpiresIn {
            return true
        }
     
        return false
    }
    
    var accessToken: String? {
        return account?.access_token
    }
    
    var isExpiresIn: Bool {
        if NSDate().compare(account!.expiresDate!) == .OrderedAscending {
            return false
        }

        return true
        
    }
    
    
    
    var account:CYUserAccount? {
        didSet {
            print("外界给我赋值了")
        }
    }
    
    static let sharedAccountViewModel: CYUserAccountViewModel = {
       
        let vm = CYUserAccountViewModel()
        
        vm.account = vm.loadAccount()
        
        return vm
    }()
    func loadAccessToken(code: String, callBack:(isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            
            "client_id": CY_APPKEY,
            "client_secret": CY_APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri":CY_REDIRECT_URL
            
        ]
        
        CYNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
//                print("\(error)")
                callBack(isSuccess: false)
                return
            }
//            print(responseObject)
            
            let account = CYUserAccount(dict: responseObject!)
//            print("Cyr:\(account)")
            
            self.loadUserInfo(account, callback: callBack)
        }
        
    }
    
    private func loadUserInfo(account:CYUserAccount,callback:(isSuccess: Bool)->()) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        guard let accessToken = account.access_token,uid = account.uid else {
            print("参数不够")
            callback(isSuccess: false)
            return
        }
        
        let parameters = [
            
            "access_token": accessToken,
            "uid": uid
            
        ]
        
        CYNetworkTools.sharedTools.requst(.GET, urlString: urlStr, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
                print("个人信息请求错误")
//                SVProgressHUD.showErrorWithStatus("个人信息请求错误")
                callback(isSuccess: false)
                return
            }
            print(responseObject)
            account.screen_name = responseObject!["screen_name"] as? String
            account.avatar_large = responseObject!["avatar_large"] as? String
            
//            let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true).last! as NSString).stringByAppendingPathComponent("account.cry")
//            print(file)
//            
//            NSKeyedArchiver.archiveRootObject(account, toFile: file)
           
            self.saveUserAccount(account)
            
            self.account = account
            
            callback(isSuccess: true)
        }
        
    }
    
    //归档
    private let archivefile = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
  
    
    private func loadAccount()-> CYUserAccount? {
        
        return NSKeyedUnarchiver.unarchiveObjectWithFile(archivefile) as? CYUserAccount
    }
    
    private func saveUserAccount(account: CYUserAccount) {
        NSKeyedArchiver.archiveRootObject(account, toFile: archivefile)
    }
  

    
    
    
    
    
 
}
